 
package c.x.jy.api.service.impl;


import java.awt.image.BufferedImage;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.code.kaptcha.Producer;

import c.x.jy.api.service.CaptchaService;
import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.DateUtils;
import c.x.jy.dao.entity.CaptchaEntity;
import c.x.jy.service.redis.Cache;
 
 
 

/**
 * 验证码
 *
 */
@Service("CaptchaService")
public class CaptchaServiceImpl   implements  CaptchaService {
    @Autowired
    private Producer producer;
    
    @Autowired
    private   Cache redisUtils;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        CaptchaEntity captchaEntity = new CaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
       // this.save(captchaEntity);
        redisUtils.set("Captcha_"+uuid, captchaEntity,300l);
        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        CaptchaEntity captchaEntity =   (CaptchaEntity) redisUtils.get("Captcha_"+uuid,CaptchaEntity.class);  // this.getOne(new QueryWrapper<CaptchaEntity>().eq("uuid", uuid));
        if(captchaEntity == null){
            return false;
        }

        //删除验证码
        //this.removeById(uuid);
        redisUtils.remove  ("Captcha_"+uuid);
        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }

	 
}
